package com.zjt.smart.ui.base;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.Window;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.umeng.analytics.MobclickAgent;
import com.zjt.smart.manager.EventManager;
import com.zjt.smart.mvp.model.Event;
import com.zjt.smart.observer.EventObserver;
import com.zjt.smart.ui.base.swipeback.SwipeBackActivity;

import java.util.List;

import butterknife.ButterKnife;

/**
 * @author zhengjianting
 * @time 2017/8/28 0028 上午 9:58
 */

public abstract class BaseActivity extends SwipeBackActivity implements EventObserver {

    private RequestManager imgRequestManager;
    protected abstract int layoutId();

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
    }

    @SuppressWarnings("ConstantConditions")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        imgRequestManager = Glide.with(this);
        if (layoutId() != 0){
            setContentView(layoutId());
        }
        ButterKnife.bind(this);
        EventManager.getInstance().regist(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
        imgRequestManager.resumeRequests();
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        EventManager.getInstance().unregist(this);
        ButterKnife.unbind(this);
        super.onDestroy();
        imgRequestManager.onTrimMemory(android.content.ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
    }

    @Override
    public void onEvent(Event event) {

    }

    public RequestManager getImgRequestManager(){
        Fragment fragment = getVisibleFragment();
        if (fragment != null && fragment instanceof BaseFragment) {
            return ((BaseFragment) fragment).getImgRequestManager();
        }
        return imgRequestManager;
    }

    public Fragment getVisibleFragment(){
        FragmentManager fragmentManager = getSupportFragmentManager();
        List<Fragment> fragments = fragmentManager.getFragments();
        if (fragments == null)
            return null;
        for(Fragment fragment : fragments){
            if(fragment != null && fragment.isVisible()&& fragment.getUserVisibleHint())
                return fragment;
        }
        return null;
    }

}
